package com.linshengjian.snowball.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by 林圣坚 on 2016/9/3.
 */
@ConditionalOnBean(IResultFormat.class)
@ControllerAdvice
public class WebResultFormatHandler {

    @Autowired
    private IResultFormat format;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exception(Exception e) {
        return format.error(e);
    }

    /**
     * 使用指定格式的返回值
     * @return
     */
    @Bean
    public WebMvcRegistrations createWebMvcRegistrations() {
        return new WebRegistrationsAdapter(format);
    }
}
